from fastapi import FastAPI
from sqlmodel import SQLModel
from apps.category.apis import router


# Create FastAPI application
app = FastAPI()

app.include_router(router)

from fastapi_amis_admin.admin import admin, settings, AdminSite, Settings
from fastapi_amis_admin.amis import PageSchema

from apps.category.models import Category

site = AdminSite(settings=Settings(database_url_async='mysql+pymysql://root:123456@192.168.3.183:3308/demo?charset=utf8mb4'))


# from sqlalchemy_database import AsyncDatabase, Database
# async_db = AsyncDatabase.create(
#     "mysql+aiomysql://root:123456@192.168.3.183:3308/demo?charset=utf8mb4",
#     echo=settings.debug,
#     session_options={"expire_on_commit": False},
# )
#
# # Create AdminSite instance
# site = AdminSite(settings=settings, engine=async_db)


@site.register_admin
class CategoryAdmin(admin.ModelAdmin):
    group_schema = PageSchema(label='Articles', icon='fa fa-wordpress')
    page_schema = PageSchema(label='分类管理', icon='fa fa-folder')
    model = Category
    search_fields = [Category.name]

# Mount the backend management system
site.mount_app(app)



# Create initial database table
@app.on_event("startup")
async def startup():
    await site.db.async_run_sync(SQLModel.metadata.create_all, is_session=False)
    # # Create a default administrator, username: admin, password: admin, please change the password in time!!!
    # await auth.create_role_user("admin")
    # #Create the default super administrator, username: root, password: root, please change the password in time!!!    await auth.create_role_user("root")
    # # Run the startup method of the site, load the casbin strategy, etc.
    # await site.router.startup()
    # #Add a default casbin rule
    # if not auth.enforcer.enforce("u:admin", site.unique_id, "page", "page"):
    #     await auth.enforcer.add_policy("u:admin", site.unique_id, "page", "page", "allow")


# Requirements: User must be logged in
# @app.get("/auth/get_user")
# @auth.requires()
# def get_user(request: Request):
#     return request.user


if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app)
